const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { authenticateToken, generateString, logUserOperation } = require('../untils/untils');

// 登录接口
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证输入参数
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 查询数据库中的用户
    const [users] = await db.execute(
      'SELECT * FROM user WHERE username = ? AND password = ?',
      [username, password]
    );

    // 检查用户名和密码是否正确
    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 判断角色是否可以登录
    if (users[0].is_active == '否') {
      return res.status(401).json({
        success: false,
        message: '用户已禁用'
      });
    }

    // 4. 生成JWT令牌
    const token = jwt.sign(
      { userId: username, username: password },
      'crm',
      { expiresIn: '1d' }
    );


    // 获取前端路由
    const [routes] = await db.execute('SELECT * FROM vue_routes');

    // 获取角色权限
    const [user_role_res] = await db.execute('SELECT role.* FROM user_role JOIN role ON user_role.role_id = role.role_id WHERE user_role.username = ? ', [users[0].username]);

    // item.mate存在null的情况
    const new_routes = routes.filter(item => {
      return item.meta !== null && user_role_res.some(role => role.permissions.includes(item.meta.title));
    });



    await logUserOperation(req, '登录', '登录', '登录成功', '成功');


    // 登录成功
    res.status(200).json({
      success: true,
      message: '登录成功',
      token: token,
      routes: new_routes
    });

  } catch (error) {
    console.error('登录错误:', error);
    await logUserOperation(req, '登录', '登录', '登录失败', '失败', error.message);

    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 退出登录
router.post('/logout', authenticateToken, async (req, res) => {
  try {
    await logUserOperation(req, '登出', '登出', '登出成功', '成功');
    res.json({
      success: true,
      message: '登出成功'
    });
  } catch (error) {
    await logUserOperation(req, '登出', '登出', '登出失败', '失败', error.message);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});


// 修改密码
router.post('/changePassword', authenticateToken, async (req, res) => {
  try {
    const { old_password, new_password } = req.body;
    const [user] = await db.execute('SELECT * FROM user WHERE username = ?', [req.user.userId]);
    if (user.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }
    if (user[0].password !== old_password) {
      return res.status(401).json({
        success: false,
        message: '旧密码错误'
      });
    }

    const sql = `UPDATE user SET password = ? WHERE username = ?`;
    const params = [new_password, req.user.userId];
    await db.execute(sql, params);
    await logUserOperation(req, '修改密码', '修改密码', '修改密码成功', '成功');
    res.json({
      success: true,
      message: '修改密码成功'
    });
  } catch (error) {
    await logUserOperation(req, '修改密码', '修改密码', '修改密码失败', '失败', error.message);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 获取当前用户信息
router.get('/getUserInfo', authenticateToken, async (req, res) => {
  try {
    const [user] = await db.execute('SELECT * FROM user WHERE username = ?', [req.user.userId]);
    const [user_role] = await db.execute('SELECT * FROM user_role WHERE username = ?', [user[0].username]);
    const [role] = await db.execute('SELECT * FROM role WHERE role_id = ?', [user_role[0].role_id]);
    const obj = {
      username: user[0].username,
      role_name: role[0].role_name,
    }
    res.json({
      success: true,
      message: '获取用户信息成功',
      data: obj
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});


module.exports = router; 